<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends MY_Controller{

	function __construct(){
		parent::__construct();
	}

	public function index(){
		$userName = $this->input->cookie('userName',true);
		$data = array(
			'userName' => $userName
		);
		$this->load->view('login',$data);
	}

	public function register(){

		$userId = $this->input->get_post('userId');
		$redirect = $this->input->get_post('redirect');
		$rmbPw = $this->input->get_post('rmbPw');
		$userName = $this->input->get_post('userName');
		// var_dump($url);exit();
		if(!$userId){
			$this->load->view('login');
			exit(0);
		}

		if($rmbPw == "true"){
			$cookie = array(
				'name' => 'userName',
				'value' => $userName,
				'expire' => 7*24*3600
			);
		}else if($rmbPw == "false"){
			if(!empty($_COOKIE['userName'])){
				// var_dump("expression");
				// exit();
				$cookie = array(
					'name' => 'userName',
					'value' => '',
					'expire' => ''
				);
			}

		}

		$user_cookie = array(
			'name' => 'userId',
			'value' => $userId,
			'expire' => '0'
		);

		$this->input->set_cookie($user_cookie);
		$this->input->set_cookie($cookie);
		$this->UsersModel->update_login_date($userId);

		if(!$redirect){
			redirect('/index');
			// header('Location:'.$url);
		}else{
			header('Location:'.$redirect);
			// $this->load->view($redirect);
		}
	}

	//退出
	public function logout(){

		$cookie = array(
			'name' => 'userId',
			'value' => '',
			'expire' => ''
		);

		$redirect = $this->input->get('redirect');

		$this->input->set_cookie($cookie);
		header('Location:'.$redirect);
	}

	//检验用户名密码是否合法
	public function ajax_check_login(){
		$userName = $this->input->get_post('userName');
		$password = $this->input->get_post('password');
		$rmbPw = $this->input->get_post('rmbPw');
		$result = $this->UsersModel->check_login($userName,$password);
		if (!empty($result)){
			$json = array('success' => true,'msg' => $result['id']);
		}else{
			$json = array('success' => false,'msg' => "用户名或密码错误");
		}
		echo json_encode($json);
		exit(0);
	}
}